package com.richmond.gui;


import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Cursor;
import javafx.scene.Parent;
import javafx.scene.layout.Pane;
import javafx.util.Duration;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.URL;

/**
 * User: csavard
 * Date: 12-09-11
 * Time: 12:12
 */
public class LockPane {

    private static final Logger LOGGER = Logger.getLogger(LockPane.class);

    public static LockPaneController lock(final Pane node) throws IOException {
        final LockPaneController lock = getLock();
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                lock.pane.setPrefSize(node.getWidth(), node.getHeight());
                lock.pane.setOpacity(0.0);
                node.getChildren().add(lock.pane);
                node.setCursor(Cursor.WAIT);

                FadeTransition fadeTransition = new FadeTransition(new Duration(500.0),lock.pane);
                fadeTransition.setFromValue(0.0f);
                fadeTransition.setToValue(1.0f);
                fadeTransition.play();
            }
        });

        return lock;
    }

    public static void unlock(final Pane node, final LockPaneController lock) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                FadeTransition fadeTransition = new FadeTransition(new Duration(500.0),lock.pane);
                fadeTransition.setFromValue(1.0f);
                fadeTransition.setToValue(0.0f);
                fadeTransition.play();

                fadeTransition.setOnFinished(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent actionEvent) {
                        node.getChildren().remove(lock.pane);
                        node.setCursor(Cursor.DEFAULT);
                    }
                });
            }
        });
    }

    private static LockPaneController getLock() throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL formUrl = classLoader.getResource("com/richmond/gui/LockPane.fxml");
        URL cssUrl = classLoader.getResource("com/richmond/gui/LockPane.css");

        FXMLLoader fxmlLoader = new FXMLLoader();
        Parent lockPane = (Parent) fxmlLoader.load(formUrl.openStream());
        lockPane.getStylesheets().add(cssUrl.toString());
        LockPaneController controller = fxmlLoader.getController();


        return controller;
    }
}
